library(tidyverse)
library(sf)
library(leaflet)
library(sfheaders)
library(htmlwidgets)
library(htmltools)
library(ggvoronoi)
library(dplyr)

rm(list=ls())

setwd <- getwd() ## assuming files in same folder!

Shikoku_villages.df <- read.table("Shikoku_Voronoi_data.txt", sep = "\t",header = TRUE)
azukari_villages <- c("伊予国_宇摩郡_西寒川村", "伊予国_越智郡_朝倉上村", "伊予国_宇摩郡_小川山村",
                      "伊予国_宇摩郡_岡銅村")

GCS <- st_crs("+proj=longlat +ellps=WGS84 +datum=WGS84")
## Japan outline pulled from https://gadm.org/download_country.html
Japan_outline <- st_read("gadm40_JPN_shp/gadm40_JPN_0.shp", quiet=TRUE)


Japan_outline <- st_transform(Japan_outline, crs = GCS)
st_crs(Japan_outline) <- GCS
Japan_outline <- st_cast(Japan_outline, "POLYGON") ## create outline map as sf polygon


#####
Shikoku_villages.df$holder_two_text <- ifelse(is.na(Shikoku_villages.df$holder_two),"",paste0("<span style='padding-left: 20px; display:block'>",
                                                                                              Shikoku_villages.df$holder_two_label, ": ", Shikoku_villages.df$holder_two_koku, " koku <p>"))

## do this next
Shikoku_villages.df$radius_holder_two_text <- ifelse(is.na(Shikoku_villages.df$holder_two_Simpson_5k),"",
        paste0("<span style='padding-left: 20px; display:block'>",Shikoku_villages.df$holder_two_Simpson_5k, " ",
               Shikoku_villages.df$radius_holder_two_romaji,": ", round(Shikoku_villages.df$holder_two_koku_Simpson_5k,4), " koku <p>"))

Shikoku_villages.df$radius_holder_three_text <- ifelse(is.na(Shikoku_villages.df$holder_three_Simpson_5k),"",
                                                     paste0("<span style='padding-left: 20px; display:block'>",Shikoku_villages.df$holder_three_Simpson_5k, " ",
                                                            Shikoku_villages.df$radius_holder_three_romaji,": ", round(Shikoku_villages.df$holder_three_koku_Simpson_5k,4), " koku <p>"))



Shikoku_villages.df$popup_text <- paste(Shikoku_villages.df$mura," ",Shikoku_villages.df$romaji_mura," village","<p>",
                                        "Main holders in village: ","<p>","<span style='padding-left: 20px; display:block'>",Shikoku_villages.df$holder_one_label, ":", Shikoku_villages.df$holder_one_koku, "koku <p>",
                                        Shikoku_villages.df$holder_two_text,
                                        "</span><p>",
                                        "Total village size: ",round(Shikoku_villages.df$total_kokudaka,4),"<p>",
                                        "No of holders in 5km radius: ", Shikoku_villages.df$Holder_count_5km_radius, "<p>",
                                        "Main holders in 5km radius: ","<p>","<span style='padding-left: 20px; display:block'>",
                                        Shikoku_villages.df$radius_holder_one_label, ":", round(Shikoku_villages.df$holder_one_koku_Simpson_5k,4), "koku <p>",
                                        Shikoku_villages.df$radius_holder_two_text,
                                        Shikoku_villages.df$radius_holder_three_text,
                                        "</span><p>",
                                        
                                        "5km radius Simpson index: ", round(Shikoku_villages.df$Simpson_5km_radius,4), "<p>",
                                        "lat: ",round(Shikoku_villages.df$lat,4),
                                        " lon: ", round(Shikoku_villages.df$lon,4)) %>% lapply(htmltools::HTML)



## sets order of legend
Shikoku_villages.df$holder_one_legend <- factor(Shikoku_villages.df$holder_one_legend, ordered = TRUE,
                                                levels = c("大洲藩 Ōzu","新谷藩 Niiya","伊予松山藩 Iyo-Matsuyama",
                                                           "宇和島藩 Uwajima","吉田藩 Yoshida","今治藩 Imabari","高知藩 Kōchi",
                                                           "Other"))

## sets color palette for legend
factpal <- colorFactor(palette = c("#1f78b4","#b2df8a","#fb9a99","#fdbf6f","#33a02c","#a6cee3","#ffff99",NA), 
                       domain = Shikoku_villages.df$holder_one_legend)


## creates mouseover labels
Shikoku_villages.df$labels <- paste0(Shikoku_villages.df$kuni," ",Shikoku_villages.df$romaji_kuni, " province","<br>",
                                     Shikoku_villages.df$gun," ",Shikoku_villages.df$romaji_gun, " county","<br>",
                                     Shikoku_villages.df$mura," ",Shikoku_villages.df$romaji_mura," village","<br>",
                                     "main holder: ", Shikoku_villages.df$holder_one_label) %>% lapply(htmltools::HTML)

## distinguish between single and multiple holders 
border_pal <- colorFactor(palette = c("grey90","red"),levels = c("single","shared"))


Shikoku_villages.sf <- st_as_sf(Shikoku_villages.df, coords = c("lon","lat"))
st_crs(Shikoku_villages.sf) <- GCS
Shikoku_villages.sf <- st_transform(Shikoku_villages.sf, crs = GCS) ## converts to proejected sf object


Shikoku.sf <- st_as_sf(Japan_outline$geometry[391]) ## creates sf object for main Shikoku

# Shikoku_villages.df <- Shikoku_villages.df[which(check_for_duplicates),]

## create dataframe for use with voronoi_polygon() 
## ggvoronoi allows for easier retention of all metadata for villages 

Shikoku.df <- data.frame(st_coordinates(Japan_outline$geometry[391]))
colnames(Shikoku.df)[1:2] <- c("lon","lat")
Shikoku_polygon.sf <- st_as_sf(ggvoronoi::voronoi_polygon(data.frame(Shikoku_villages.df),x="lon",y="lat",outline = data.frame(Shikoku.df)))
## then reduce annotated map to just Iyo
Shikoku_polygon.sf <- Shikoku_polygon.sf[which(Shikoku_polygon.sf$kuni=="伊予国"),] ## need data for all of Shikoku to get correct border polygons


## add other islands 
island_number <- 892 ## Nakajima
## get villages within Nakajima islands
Nakajima_vector <- unlist(st_contains(Japan_outline$geometry[island_number],Shikoku_villages.sf))
## convert Nakajima to dataframe for use with voronoi_polygon()
island_outline_temp.df <- data.frame(st_coordinates(Japan_outline$geometry[island_number]))

Nakajima_polygon.sf <- st_as_sf(voronoi_polygon(data.frame(Shikoku_villages.df[Nakajima_vector,]),
                                                x="lon",y="lat",
                                                outline = data.frame(island_outline_temp.df)))
## add islands without villages
## need to hand code values since they are not populated by village data

extra_islands.df <- data.frame(matrix(rep(NA,5*ncol(Shikoku_polygon.sf)),byrow = TRUE,nrow = 5))
colnames(extra_islands.df) <- colnames(Shikoku_polygon.sf)

extra_islands.df$geometry[1] <- Japan_outline$geometry[891] # 怒和島 Nuwa Island
extra_islands.df$geometry[2] <- Japan_outline$geometry[459] # 青島 Ao Island
extra_islands.df$geometry[3] <- Japan_outline$geometry[509] # 睦月島 Muzuki Island
extra_islands.df$geometry[4] <- Japan_outline$geometry[906] # 大館場島 Ōtabachijima 
extra_islands.df$geometry[5] <- Japan_outline$geometry[913] # 小館場島 Kotabachijima 


extra_islands.df$holder_one <- "大洲藩"
extra_islands.df$holder_one_legend <- "大洲藩 Ōzu"


extra_islands.df$popup_text <- c("Nuwajima Island 怒和島","Aojima Island 青島",
                                 "Muzukijima Island 睦月島", "Ōtachibajima 大館場島<br>In the later Tokugawa era, the island was uninhabited common land by Nyō and Yoshiki villages (Ōzu domain) on neighboring Nakajima Island","Kotabachijima 小館場島<br>In the later Tokugawa era, the island was uninhabited common land held by Uwama and Kumata villages (Ōzu domain) on neighboring Nakajima Island")


extra_islands.df$labels <- c("Nuwajima Island 怒和島","Aojima Island 青島",
                             "Muzukijima Island 睦月島", "Ōtachibajima Island 大館場島","Kotabachijima Island 小館場島")



extra_islands.sf <- st_as_sf(extra_islands.df)



map_title <- "Iyo Province 伊予国 and select islands"


complete.sf <- rbind(Shikoku_polygon.sf,Nakajima_polygon.sf,extra_islands.sf)

complete.sf$annotation <- NA


complete.sf$annotation <- ifelse(complete.sf$mura%in%c("小浜村","大浦村","粟井村","宇和間村"), paste0("The village of ",
                                                                                         complete.sf$mura," ",complete.sf$romaji_mura, 
                                                                                         " appears in KKT as the holding of Tosa/Kōchi domain, although historically it was a \"loaned land\" or <i>azukarichi</i>, that was held by the shogunate, but often administered by Ōzu domain. The transfer to the village to Tosa was likely part of the reallocation of peripheral Tokugawa holdings."), complete.sf$annotation)



complete.sf$popup_text_annotated <- paste(complete.sf$village_label," village","<p>",
                                          "Holders: ","<p>","<span style='padding-left: 20px; display:block'>",complete.sf$holder_one_label, ":", complete.sf$holder_one_koku, "koku <p>",
                                          complete.sf$blurb_two,
                                          complete.sf$blurb_three,
                                          "</span><p>",
                                          "Total size: ",round(complete.sf$total_kokudaka,4),"<p>",
                                          "lat: ",round(complete.sf$lat,4),
                                          " lon: ", round(complete.sf$lon,4),"<p>",
                                          complete.sf$annotation)


complete.sf$popup_text <- ifelse(is.na(complete.sf$annotation),complete.sf$popup_text,complete.sf$popup_text_annotated)

complete.sf$labels <- complete.sf$labels %>% lapply(htmltools::HTML)

###

final_map <- leaflet(complete.sf) %>%
  addProviderTiles("Esri.WorldImagery",
                   options = providerTileOptions(minZoom = 8, maxZoom = 20)) %>%
  addPolygons(fillColor = factpal(complete.sf$holder_one_legend), smoothFactor = 0.2,
              fillOpacity = 1,
              stroke = TRUE,
              highlightOptions = highlightOptions(color = "grey80", weight = 2,
                                                  bringToFront = TRUE),
              label = complete.sf$labels,
              popup = complete.sf$popup_text,
              color = "grey80",
              weight = 2,
              group = "Voronoi borders") %>%
  addCircleMarkers(lng = complete.sf$lon, lat=complete.sf$lat,
                   radius = 2,
                   color= factpal(complete.sf$holder_one_legend),
                   popup = complete.sf$popup_text,
                   label = complete.sf$labels,
                   # stroke = FALSE, 
                   fillOpacity = 0.8,
                   group = "Villages") %>%
  addLayersControl(
    baseGroups = c("Voronoi borders","Villages"),
    options = layersControlOptions(collapsed = FALSE)
  ) %>%
  addLegend(position = "bottomright", pal = factpal, values = complete.sf$holder_one_legend) %>%
  setView(lat= 33.6, lng = 132.9, zoom = 8) %>% 
  addControl(map_title, position = "topleft") %>%
  addMeasure(
    position = "topleft",
    primaryLengthUnit = "meters",
    primaryAreaUnit = "sqmeters",
    activeColor = "#0bd3d3",
    completedColor = "#f890e7") 

    

## can ignore warning -- village coords are missing for islands without villages!
final_map
saveWidget(final_map, "Figure_11_Interactive_map_of_Iyo.html")

